package com.jt.www.biz.order_pc.service.impl;

import com.google.common.collect.Lists;
import com.jt.www.biz.order_pc.service.PolicyService;
import com.jt.www.model.param.policy.PolicyForAppCaseQo;
import com.jt.www.model.param.policy.RenewalQo;
import com.jt.www.model.remote.product.RiskInfoVo;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.model.vo.policy.EduIndexMsgVO;
import com.jt.www.model.vo.policy.PolicyFormAppCaseVO;
import com.jt.www.model.vo.policy.PolicyRiskInfoVo;
import com.jt.www.model.vo.policy.RenewalVO;
import com.jt.www.remote.ProductClient;
import com.jt.www.remote.ins.InsClient;
import com.jt.www.util.DateUtils;
import com.jt.www.util.JsonUtil;
import com.jt.www.util.RedisUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.stream.Collectors;

@Service
public class PolicyServiceImpl implements PolicyService {
    public static final Logger log = LoggerFactory.getLogger(PolicyServiceImpl.class);
    private final static String CHANNEL_NO = "edu";
    //报案关联保单出险人不同被保险人时只展示我学保责任险保单 徐州学平险-监护人责任险：19XZ131228,20XZ827943；监护无忧-监护人责任保险：20XZ753558
    private final static String WXB_ZRX_RISK_CODE = "19XZ131228,20XZ753558,20XZ827943";
    @Autowired
    private InsClient insClient;
    @Autowired
    private ProductClient productClient;

    @Override
    public ResponseEntity selectRenewalList(RenewalQo renewalQo, String findCode) throws Exception {

        String MESSAGE_LOCK_KEY = "EDU_RENEWAL_" + renewalQo.getUserCode() + DateUtils.conver(new Date(), DateUtils.DATE_FORMAT_YYYY_MM_DD);//锁前缀

        // 如果一个定时任务在执行，那么下一个定时不能执行
        if (RedisUtil.setSixHoursLock(MESSAGE_LOCK_KEY)) {
            log.info(findCode + "我学保续保保单列表查询接口 投保中心请求开始时间{}", System.currentTimeMillis());
            GenericListResponse<RenewalVO> result = insClient.selectEduRenewalList(renewalQo);
            log.info(findCode + "我学保续保保单列表查询接口 投保中心请求结果{}", JsonUtil.object2Json(result));
            log.info(findCode + "我学保续保保单列表查询接口 投保中心请求结束时间{}", System.currentTimeMillis());

            return GenericListResponse.listAndCount(result.getList(), result.getTotal());
        } else {
            log.info("我学保续保保单列表查询接口==>当天任务已经执行，不在重复执行");
            return GenericListResponse.listAndCount(null, 0L);
        }

    }

    @Override
    public GenericListResponse<PolicyFormAppCaseVO> selectPolicyForAppCase(PolicyForAppCaseQo policyForAppCaseQo, String findCode) throws Exception {

        log.info(findCode + "索赔小程序保单列表查询接口 投保中心请求开始时间{}", System.currentTimeMillis());

        /*if(StringUtils.isNotBlank(policyForAppCaseQo.getRiskPersonLicenceNo())){
            List<String> appCodeList = endorseMapper.selectEndorseByNameAndCardNo(null, policyForAppCaseQo.getRiskPersonLicenceNo());
            if(appCodeList != null && appCodeList.size() > 0){
                policyForAppCaseQo.setAppCodes(appCodeList);
            }
        }*/

        GenericListResponse<PolicyFormAppCaseVO> result = insClient.selectEduPolicyForAppCase(policyForAppCaseQo);

        //出险人同被保险人：1-是(学平险)；0-否(监护人责任险)；
        if (StringUtils.isNotBlank(policyForAppCaseQo.getIsSameInsured()) && result.getTotal() > 0) {
            if ("0".equals(policyForAppCaseQo.getIsSameInsured())) {
                result.setList(result.getList().stream().filter(v -> WXB_ZRX_RISK_CODE.contains(v.getMainRiskCode())).collect(Collectors.toList()));
            } else {
                result.setList(result.getList().stream().filter(v -> !WXB_ZRX_RISK_CODE.contains(v.getMainRiskCode())).collect(Collectors.toList()));
            }
            result.setTotal(result.getList().size());
        }

        log.info(findCode + "索赔小程序保单列表查询接口 投保中心请求结束时间{}", System.currentTimeMillis());

        return result;
    }

    @Override
    public ResponseEntity<GenericListResponse<RiskInfoVo>> selectRiskList(String appCode, String productCode, String findCode) throws Exception {
        log.info(findCode + "附加险列表查询接口 投保中心请求开始时间{}", System.currentTimeMillis());

        // 根据产品编码查询该产品所有附加险
        GenericListResponse<RiskInfoVo> productRisk = productClient.searchRiskByProductCode(productCode, CHANNEL_NO);
        if (!"0000".equals(productRisk.getCode())) {
            return GenericListResponse.listAndCount(Lists.newArrayList(), 0L);
        } else {
            // 根据投保单号查询该投保单选择的附加险
            GenericListResponse<PolicyRiskInfoVo> policyRisk = insClient.selectRiskByAppCode(appCode);
            if (!"0000".equals(policyRisk.getCode())) {
                return GenericListResponse.listAndCount(Lists.newArrayList(), 0L);
            } else {
                if (productRisk.getTotal() > 0) {
                    productRisk.getList().forEach(v -> {
                        v.setIsSelected(false);
                        if (policyRisk.getList() != null && policyRisk.getList().size() > 0) {
                            policyRisk.getList().forEach(pv -> {
                                if (pv.getRiskCode().equals(v.getCode())) {
                                    // 如果该保单选择了此附加险，设置为true
                                    v.setIsSelected(true);
                                }
                            });
                        }
                    });
                    productRisk.getList().removeIf(obj -> "M".equals(obj.getRiskFlag()));
                    productRisk.setTotal(productRisk.getList().size());
                }
            }
        }

        log.info(findCode + "附加险列表查询接口 投保中心请求结束时间{}", System.currentTimeMillis());
        return GenericListResponse.listAndCount(productRisk.getList(), productRisk.getTotal());
    }

    @Override
    public GenericListResponse<EduIndexMsgVO> selectEduIndexMsg() throws Exception {

        // 业务端时实保单信息查询 最近已出单状态的前10条
        GenericListResponse<EduIndexMsgVO> res = insClient.selectEduIndexMsg();

        return res;
    }
}
